package com.urban.pooling.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;

import com.urban.pooling.domain.User;
import com.urban.pooling.repository.UserRepository;

public class CustomAuthenticationProvider implements AuthenticationProvider {
	@Autowired
	private UserRepository userDao;

	@Override
	public Authentication authenticate(Authentication authentication)
			throws AuthenticationException {
		String userOrEmail = authentication.getName();
		String pass = (String) authentication.getCredentials();
		String hashedPassword = null;
		Boolean validAuth = false;

		User user = null;

		// check if user tries to login using email
		if (userOrEmail.contains("@")) {
			user = userDao.findByEmail(userOrEmail);
		} else {
			user = userDao.findByUsername(userOrEmail);
		}

		if (user != null) {
			// check authentication password against user's password
			hashedPassword =pass; //SecurityUtil.hashPassword(pass, user.getSalt()); TODO : hash the passwords
			if (hashedPassword.equals(user.getPasswordHash())) {
				validAuth = true;
			}
		}
		//TODO : check for disabled and locked accounts (against brute force)
		
		if(! validAuth){
			throw new BadCredentialsException("Failed to authenticate.");
		}
		
		UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
				user.getUsername(), "***", SecurityUtil.getAuthorities(user));

		return authToken;
	}

	@Override
	public boolean supports(Class<?> authentication) {
		if(authentication.equals(UsernamePasswordAuthenticationToken.class))
			return true;
		return false;
	}

}
